/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cmc.rra.service.impl;

import com.cmc.rra.service.AppUserService;
import com.cmc.rra.sub.AppUser;
import com.cmc.rra.utils.HibernateUtils;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author CMC
 */
public class AppUserServiceImpl implements AppUserService{

    @Override
    public AppUser authenticate(String userName, String password) {
        Session session = HibernateUtils.currentSession();
        AppUser appUser = null;
        try{
            Query query = session.createQuery("from AppUser appuser where appuser.userName=:userName and appuser.password=:password");
            query.setString("userName", userName);
            query.setString("password", password);
            appUser = (AppUser) query.uniqueResult();
        }catch(Exception exception){
            exception.printStackTrace();
        }finally{
            HibernateUtils.closeSession();
        }
        return appUser;
    }

    @Override
    public List<AppUser> getAll() {
        Session session = HibernateUtils.currentSession();
        List<AppUser> appUserList = null;
        try{
            Query query = session.createQuery("from AppUser");
            appUserList = (List<AppUser>) query.list();
        }catch(Exception exception){
            exception.printStackTrace();
        }finally{
            HibernateUtils.closeSession();
        }
        return appUserList;
    }

    @Override
    public void create(AppUser appUser) {
        Session session = HibernateUtils.currentSession();
        Transaction tx = null;
        boolean rollback = true;
        try {
            tx = session.beginTransaction();
            session.saveOrUpdate(appUser);
            tx.commit();
            rollback = false;
        } catch (Exception exception) {
            exception.printStackTrace();

        } finally {
            if (rollback && tx != null) {
                tx.rollback();
            }
            HibernateUtils.closeSession();
        }
    }

    @Override
    public AppUser findByGuid(String guid) {
        Session session = HibernateUtils.currentSession();
        AppUser appUser = null;
        try{
        
            Query  query = session.createQuery("from AppUser appUser where appUser.guid=:guid");
            query.setString("guid", guid);
            appUser = (AppUser) query.uniqueResult();        
        }catch(Exception exception){
            exception.printStackTrace();
        }finally{
            HibernateUtils.closeSession();
        }
        return appUser;
    }
    
}
